import { Button, message, Spin, Table, Tabs } from 'antd'
import Filter from '@/components/filter'
import React, { useEffect, useMemo, useState } from 'react'
import http from '@/utils/request'
import type { DictItem, optionConfigType } from '@/types'
import './index.scss'

interface filteType {
  [key: string]: any,
  provinceCode?: string,
  cityCode?: string,
  areaCode?: string,
  bizTeamId?: string,
  seatTeamId?: string,
  bizTypeId?: string,
  comboId?: string,
  endTime?: string,
  startTime?: string,
  timeRange?: string
}

const initfilter: filteType = {
  provinceCode: undefined,
  cityCode: undefined,
  areaCode: undefined,
  bizTeamId: undefined,
  bizTypeId: undefined,
  comboId: undefined,
  endTime: undefined,
  seatTeamId: undefined,
  startTime: undefined
}
const filterData: filteType = {
  ...initfilter
}

const Analysis: React.FC = () => {

  const [loading, setLoading] = useState(true)

  const [optionConfig, setOptionConfig] = useState<optionConfigType>({
    bizTeams: [],
    seatTeams: [],
    bizTypes: [],
    comboIds: [],
    gifts: []
  })
  const setOptionByKey = (key: string, val: DictItem[]) => {
    setOptionConfig((optionConfig) => ({
      ...optionConfig,
      [key]: val
    }))
  }
  const operateDataList = () => {
    return [
      {
        label: '业务团队',
        labelKey: 'teamName',
        url: '/disp/biz/team/page',
        dictName: 'bizTeams',
        params: {
          teamType: 'Biz'
        }
      },
      {
        label: '坐席团队',
        labelKey: 'teamName',
        url: '/disp/biz/team/page',
        dictName: 'seatTeams',
        params: {
          teamType: 'Seats'
        }
      }
    ].map(requestItem => {
      setLoading(true)
      return http.post(requestItem.url, {
        ...(requestItem.params || {}),
        pageNum: 1,
        pageSize: 99999,
        status: 'Enable'
      }).then(res => {
        const options = (res?.data?.list || []).map((item: { [requestItem.labelKey]: string, id: string }) => {
          return {
            value: item.id,
            label: item[requestItem.labelKey],
            disabled: item.status !== 'Enable',
            teamType: item.teamType || ''
          }
        })
        setOptionByKey(requestItem.dictName, options)
      }).finally(() => {
        setLoading(false)
      })
    })
  }

  useEffect(() => {
    operateDataList()
  }, [])

  const [queryType, setQueryType] = useState<string>('Biz')

  const filterItems = useMemo(() => {
    const teamList = queryType === 'Biz' ? [
      {
        type: 'select',
        key: 'bizTeamId',
        label: '业务团队',
        options: optionConfig.bizTeams
      }
    ] : [
      {
        type: 'select',
        key: 'seatTeamId',
        label: '坐席团队',
        options: optionConfig.seatTeams
      }
    ]
    return [
      ...teamList,{
        type: 'RangePicker',
        key: 'timeRange',
        label: '时间范围'
      }]
  }, [optionConfig, queryType])

  const filterChange = (val: any, key: keyof filteType) => {
    if (key === 'timeRange') {
      filterData.startTime = val ? val[0].format('YYYY-MM-DD HH:mm:ss') : ''
      filterData.endTime = val ? val[1].format('YYYY-MM-DD HH:mm:ss') : ''
    } else {
      filterData[key] = val
    }
  }

  const [dataSource, setDataSource] = useState<any[]>([])

  useEffect(() => {
    queryPageList()
  }, [queryType])
  
  const queryPageList = async () => {
    setLoading(true)
    const url = queryType === 'Seats' ? '/disp/biz/analysis/listDataStatisticsForSeat' : '/disp/biz/analysis/listDataStatisticsForBiz'
    const res = await http.post(url, filterData)
    setLoading(false)
    const sum = (res.data || []).reduce((obj:any, cur:any) => {
      const {
        assignmentNum,
        successNum,
        createNum,
        rescheduleNum
      } = obj
      return {
        ...obj,
        assignmentNum: assignmentNum + (cur.assignmentNum || 0),
        successNum: successNum + (cur.successNum || 0),
        createNum: createNum + (cur.createNum || 0),
        rescheduleNum: rescheduleNum + (cur.rescheduleNum || 0)
      }
    }, {
      username: '总计',
      userCode: '-',
      assignmentNum: 0,
      successNum: 0,
      createNum: 0,
      rescheduleNum: 0
    })
    setDataSource([...(res.data || []), sum])
  }

  const exportList = () => {
    const url = queryType === 'Seats' ? '/disp/biz/analysis/exportDataStatisticsForSeat' : '/disp/biz/analysis/exportDataStatisticsForBiz'
    setLoading(true)
    http.post(url, filterData, {
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      }
    }).then(res => {
      // 兼容不同后端返回的content-disposition格式
      let fileName = '统计数据.xlsx'
      const disposition = res.headers['content-disposition'] || res.headers['Content-Disposition']
      if (disposition) {
        const match = disposition.match(/filename[^;=\n]*=((['\"]).*?\2|[^;\n]*)/)
        if (match && match[1]) {
          fileName = decodeURIComponent(match[1].replace(/['"]/g, ''))
        }
      }
      const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      const link = document.createElement('a')
      link.download = fileName
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob)
      document.body.appendChild(link)
      link.click()
      URL.revokeObjectURL(link.href)
      document.body.removeChild(link)
    }).catch(err => {
      console.error('导出失败:', err)
      message.error('导出失败')
    }).finally(() => {
      setLoading(false)
    })
  }

  const tabs = [{
    key: 'Biz',
    label: '业务'
  }, {
    key: 'Seats',
    label: '坐席'
  }]

  const columns = useMemo(() => {
    return [{
      title: '姓名',
      dataIndex: 'username',
      key: 'userCode'
    }, {
      title: '工号',
      dataIndex: 'userCode',
      key: 'userCode'
    }, {
      title: '派单总数量',
      dataIndex: 'assignmentNum',
      key: 'userCode'
    }, queryType === 'Biz' ? {
      title: '改约数量',
      dataIndex: 'rescheduleNum',
      key: 'userCode'
    } : {
      title: '创建数量',
      dataIndex: 'createNum',
      key: 'userCode'
    }, {
      title: '成功数量',
      dataIndex: 'successNum',
      key: 'userCode'
    }]
  }, [queryType])

  return (
    <div className="page">
      <Tabs defaultActiveKey={queryType} items={tabs} onChange={setQueryType}/>
      <Spin spinning={loading}>
        <Filter
          items={filterItems}
          onChange={filterChange}
          onSure={queryPageList}
          otherBtn={
            <Button className="btn" onClick={exportList}>导出</Button>
          }/>
        <Table
          dataSource={dataSource}
          scroll={{ x: 'max-content' }}
          columns={columns}
          rowKey="id" />
      </Spin>
    </div>
  )
}
export default Analysis